Python binary转ASCII用法及代码示例 | 您所在的位置:网站首页 › 字符串转ascii python › Python binary转ASCII用法及代码示例 |
在本文中,我们将看到 Python 编程语言中二进制到 ASCII 的转换。有多种方法可以执行此转换,如下所示: 方法一:通过使用比纳斯奇模块Binascii 有帮助在二进制和各种 ASCII-encoded 二进制表示之间转换。 b2a_uu() 函数:这里的 “uu” 代表“UNIX-to-UNIX 编码”,它负责根据指定的程序将数据从字符串转换为二进制和 ASCII 值。 b2a_uu() 函数用于将指定的二进制字符串转换为其对应的 ASCII 等价物。 用法:b2a_uu(Text)参数:此函数接受一个参数,如下所示: Text:这是指定的二进制字符串,它将被转换为其 ASCII 等价物。Return Values:此函数返回 ASCII 等效项。 示例:将二进制转换为 ASCII。Python3 # Python program to illustrate the # conversion of Binary to ASCII # Importing binascii module import binascii # Initializing a binary string Text = b"GFG is a CS Portal" # Calling the b2a_uu() function to # Convert the binary string to ascii Ascii = binascii.b2a_uu(Text) # Getting the ASCII equivalent print(Ascii)输出: b"21T9'(&ES(&$@0U,@4&]R=&%L\n"方法二:使用Built-in 类型。这里我们将使用 内置 类型将二进制转换为 ASCII 值。 首先调用 int(binary_sting, base),base 为 2,表示二进制字符串。然后调用int.to_bytes(byte_number, byte_order)函数,其中byte_order为“big”,byte_number为binary_int占用的字节数,返回一个字节数组。这个 byte_number 可以使用操作 binary_int.bit_length() + 7 //8 找到。然后调用 array.decode 操作将数组转换为 ASCII 文本。 示例:将二进制转换为 ASCIIPython3 # Python program to illustrate the # conversion of Binary to ASCII # Initializing a binary string in the form of # 0 and 1, with base of 2 binary_int = int("11000010110001001100011", 2); # Getting the byte number byte_number = binary_int.bit_length() + 7 // 8 # Getting an array of bytes binary_array = binary_int.to_bytes(byte_number, "big") # Converting the array into ASCII text ascii_text = binary_array.decode() # Getting the ASCII value print(ascii_text)输出: abc |
CopyRight 2018-2019 实验室设备网 版权所有 |